<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqUserInfo,
  reqAddOrUpdateUser,
  reqSetUserRole,
  reqAllRole,
  reqRemoveUser,
  reqSelectUser,
} from '@/api/acl/user/index'
import { ElMessage } from 'element-plus'
// import useUserStore from '@/store/modules/user'
import useLayoutStore from '@/store/modules/setting'
// 分页器数据
let currentPage = ref<number>(1)
let pageSize = ref<number>(5)
let total = ref<number>(10)
//获取仓库中的用户信息
// const userInfo = useUserStore()
//人员信息
let personArr = ref<any>([])
// 控制添加修改的抽屉显示
let drawer = ref<boolean>(false)
// 控制分配角色的抽屉
let drawer1 = ref<boolean>(false)
// 收集发请求的用户数据
let userParams = reactive<any>({
  username: '',
  name: '',
  password: '',
})
//批量删除的用户存储
let removeUser = ref<any>([])
//仓库中的数据
let userStoreData = useLayoutStore()
// 获取用户信息
const getUserInfo = async (pager = 1) => {
  currentPage.value = pager
  const res = await reqUserInfo(
    currentPage.value,
    pageSize.value,
    searchKeyword.value ? searchKeyword.value : '',
  )
  // console.log('userInfo', res)
  if (res.code == 200) {
    personArr.value = res.data.records
  }
}

// 添加用户按钮的回调
const addUser = () => {
  drawer.value = true
  //这里要清除form表单里面的校验错误信息，但是在第一次挂载时点击按钮时form组件还没挂载，如果直接使用form组件实例的方法会报错，使用nextTick保证可以拿到
  Object.assign(userParams, {
    id: 0,
    username: '',
    name: '',
    password: '',
  })
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}
// 抽屉取消按钮
const cancel = () => {
  drawer.value = false
}
// 获取表单的实例
const formRef = ref()

//搜索携带的关键字
let searchKeyword = ref('')
// 抽屉保存按钮回调
const save = async () => {
  await formRef.value.validate() //el-form实例自带校验方法
  let res = await reqAddOrUpdateUser(userParams)
  // console.log('添加修改用户信息的返回', res)
  // console.log('表单实例', formRef.value)
  if (res.code == 200) {
    drawer.value = false
    ElMessage({
      type: 'success',
      message: userParams.id ? '编辑成功' : '添加成功',
    })
    getUserInfo(userParams.id ? currentPage.value : 1)
    // 刷新防止修改当前的用户名之后未更新
    window.location.reload()
  } else {
    drawer.value = false
    ElMessage({
      type: 'error',
      message: userParams.id ? '编辑失败' : '添加失败',
    })
  }
}
// 自定义校验规则,在表单失去焦点后执行
const validatorUsername = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户名字至少五位'))
  }
}
const validatorname = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户昵称至少五位'))
  }
}
const validatorPassword = (rule: any, value: any, callBack: any) => {
  //用户名字|昵称,长度至少五位
  if (value.trim().length >= 6) {
    callBack()
  } else {
    callBack(new Error('用户密码至少六位'))
  }
}
// 表单校验规则对象
const rules = {
  //用户名字
  username: [{ required: true, trigger: 'blur', validator: validatorUsername }],
  //用户昵称
  name: [{ required: true, trigger: 'blur', validator: validatorname }],
  //用户的密码
  password: [{ required: true, trigger: 'blur', validator: validatorPassword }],
}
onMounted(() => {
  getUserInfo()
})

// 用户编辑按钮回调
const updateUser = (row: any) => {
  drawer.value = true
  Object.assign(userParams, row)
  // 删除上次表单校验留下的错误提示
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}
//页码数变化时的回调
const handler = () => {
  getUserInfo()
}
// 静态角色数组
const role = ref<any>()
// 用户选择的角色
let selectRole = ref<any>()

// 点击分配角色的回调（获取全部角色信息）
const allocaeRole = async (row: any) => {
  // 更新已有的用户信息
  Object.assign(userParams, row)
  let res = await reqAllRole(userParams.id)
  // console.log('角色信息', res)
  if (res.code == 200) {
    role.value = res.data.allRolesList
    selectRole.value = res.data.assignRoles
    drawer1.value = true
  }
  // console.log('用户已有身份', selectRole.value)
}

// 多选框
let checkAll = ref(false)
// 选择框不确定样式
let isIndeterminate = ref(true)
// 全选框被点击
const handleCheckAllChange = (val: any) => {
  selectRole.value = val ? role.value : []
  isIndeterminate.value = false //不确定框
}
// 复选框被点击触发
const checkChange = (val: string[]) => {
  const checkCount = val.length
  // console.log('点击的个数', val.length)
  checkAll.value = checkCount === role.value.length
  isIndeterminate.value = checkCount !== role.value.length
}
//角色已分配、确定
const confirmRole = async () => {
  let data = {
    roleIdList: selectRole.value.map((item: any) => item.id),
    userId: userParams.id,
  }
  // console.log('分配角色需要请求的参数',data)

  let res = await reqSetUserRole(data)

  // console.log(res)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '分配成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: '分配失败',
    })
  }
  drawer1.value = false
  // getUserInfo()
}

const Rolecancel = () => {
  drawer1.value = false
}

//删除用户
const deleteUser = async (userId: any) => {
  const res = await reqRemoveUser(userId)
  // console.log(res)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
  getUserInfo()
}

//批量删除用户的复选框变化
const selectChange = (val: any) => {
  removeUser.value = val
  // console.log(val)
}
//批量删除按钮点击事件
const deleteBatchUser = async () => {
  let idList = removeUser.value.map((item: any) => item.id)
  // console.log(idList)

  let res: any = await reqSelectUser(idList.value)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '批量删除成功',
    })
  } else {
    ElMessage({
      type: 'error',
      message: '批量删除失败',
    })
  }
  getUserInfo()
}
//搜索事件回调
const search = () => {
  getUserInfo()
  searchKeyword.value = ''
}

const refresh = () => {
  // console.log(userStoreData.refresh)
  userStoreData.refresh = !userStoreData.refresh
}
</script>

<template>
  <el-card>
    <el-form
      :inline="true"
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <el-form-item label="用户名">
        <el-input
          placeholder="请输入查询的用户名"
          v-model="searchKeyword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          size="default"
          :disabled="searchKeyword ? false : true"
          @click="search"
        >
          搜索
        </el-button>
        <el-button @click="refresh">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!-- 表格数据 -->
  <el-card style="margin: 10px 0px">
    <el-button type="primary" size="default" @click="addUser">
      添加用户
    </el-button>
    <el-button
      type="primary"
      size="default"
      :disabled="removeUser.length > 0 ? false : true"
      @click="deleteBatchUser"
    >
      批量删除
    </el-button>
    <!-- table展示用户信息 -->
    <el-table
      @selection-change="selectChange"
      style="margin: 10px 0px"
      border
      :data="personArr"
    >
      <el-table-column type="selection" align="center"></el-table-column>
      <el-table-column label="#" align="center" type="index"></el-table-column>
      <el-table-column label="ID" align="center" prop="id"></el-table-column>
      <el-table-column
        label="用户名字"
        align="center"
        prop="username"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户名称"
        align="center"
        prop="name"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户角色"
        align="center"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="300px" align="center">
        <template #="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="User"
            @click="allocaeRole(row)"
          >
            分配角色
          </el-button>
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateUser(row)"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定要删除${row.username}?`"
            width="260px"
            @confirm="deleteUser(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 7, 9, 11]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @current-change="getUserInfo"
      @size-change="handler"
    />
  </el-card>
  <!-- 添加更新账号 -->
  <el-drawer v-model="drawer">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>{{ userParams.id ? '编辑账号' : '添加账号' }}</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form ref="formRef" :model="userParams" :rules="rules">
        <el-form-item label="用户姓名" prop="username">
          <el-input
            placeholder="请您输入用户姓名"
            v-model="userParams.username"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户昵称" prop="name">
          <el-input
            placeholder="请您输入用户昵称"
            v-model="userParams.name"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input
            placeholder="请您输入用户密码"
            v-model="userParams.password"
          ></el-input>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 分配职位的抽屉 -->
  <el-drawer v-model="drawer1">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>分配角色</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form>
        <el-form-item label="用户姓名">
          <el-input v-model="userParams.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="职位列表">
          <el-checkbox
            v-model="checkAll"
            :indeterminate="isIndeterminate"
            @change="handleCheckAllChange"
          >
            全选
          </el-checkbox>
          <el-checkbox-group v-model="selectRole">
            <el-checkbox
              v-for="item in role"
              :key="item"
              :label="item"
              @click="checkChange"
            >
              {{ item.roleName }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button @click="Rolecancel">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<style scoped></style>
